#include "stm32f4xx.h"
#include "stm32f4xx_gpio.h"
#include "stm32f4xx_tim.h"
#include "stm32f4xx_rcc.h"
#include "misc.h"
#include "cx_pwm.h"
#include "cx_encode_read.h"
#include "periphal_init.h"

volatile uint32_t SysTickTime = 0;

cx_int32_t motor_encoder_count = 0;

void get_motor_encoder_cb(cx_uint32_t time, void *args)
{
    motor_encoder_count += (TIM2->CNT) - (0xffffffff>>1);
    TIM2->CNT = 0xffffffff >> 1;
}

cx_encoder_read_event_t motor_velocity_read = 
{
    .attr = CX_ENCODER_READ_ATTR_TRIGGER_TYPE_CONTINIOUS,
    .func_cb = get_motor_encoder_cb,
    .args = CX_NULL
};

void delay_ms(uint32_t ms)
{
    SysTickTime = ms;
    while(SysTickTime != 0);
}

int nop_func(void)
{
	return -1;
}

int main(void)
{
    SysTick_Config(SystemCoreClock / 1000);
    PeripheralInitialize();

    cx_encoder_read_register(&motor_velocity_read);


    while(1)
    {
			nop_func();
        
    }
}

void TIM6_DAC_IRQHandler(void)
{
    if(TIM_GetITStatus(TIM6, TIM_IT_Update) == SET)
    {
        cx_encoder_read_cb_handler();
        TIM_ClearITPendingBit(TIM6, TIM_IT_Update);
        TIM_ClearFlag(TIM6, TIM_FLAG_Update);
    }
}

void SysTick_Handler(void)
{
    if(SysTickTime > 0)
    {
        SysTickTime--;
    }
}

